﻿const Category = require("../models/category");
const Book = require("../models/book");
const logger = require("../config/logger");

exports.getCategories = async (ctx) => {
  const categories = await Category.findAll({ include: Book });

  ctx.body = { code: 200, message: "查询图书类别列表成功", data: categories };
};

exports.addCategory = async (ctx) => {
  const { categoryName } = ctx.request.body;

  const newCategory = await Category.create({ categoryName });

  ctx.body = { code: 200, message: "添加类别成功", data: null };
};

exports.deleteCategory = async (ctx) => {
  const categoryId = ctx.params.categoryId;

  await Category.destroy({
    where: {
      categoryId,
    },
  });

  ctx.body = { code: 200, message: "删除图书类别成功", data: null };
};

exports.updateCategory = async (ctx) => {
  logger.info("要修改的类别信息：\n", ctx.request.body);

  const { categoryId, categoryName } = ctx.request.body;

  await Category.update({ categoryName }, { where: { categoryId } });

  ctx.body = { code: 200, message: "修改图书类别成功", data: null };
};
